let websocket = null;
let messageCallback = null;
let errorCallback = null;
let closeCallback = null;
let connectCallback = null;

// WebSocket连接地址
const wsUrl = process.env.VUE_APP_BASE_API.replace('http://', 'ws://').replace('https://', 'wss://');

export function initWebSocket(deviceId, options = {}) {
  if (typeof (WebSocket) === 'undefined') {
    console.error('您的浏览器不支持WebSocket');
    return false;
  }

  // 设置回调函数
  messageCallback = options.onMessage;
  errorCallback = options.onError;
  closeCallback = options.onClose;
  connectCallback = options.onOpen;

  try {
    websocket = new WebSocket(wsUrl + 'websocket/iot/' + deviceId);
    initEventHandle();
  } catch (e) {
    console.error('WebSocket连接错误:', e);
    reconnect(deviceId);
  }
}

// 初始化事件处理
function initEventHandle() {
  // 连接成功
  websocket.onopen = () => {
    console.log('WebSocket连接成功');
    heartCheck.reset().start();
    connectCallback && connectCallback();
  };

  // 收到消息
  websocket.onmessage = (event) => {
    console.log('收到消息:', event.data);
    heartCheck.reset().start();
    messageCallback && messageCallback(event.data);
  };

  // 连接关闭
  websocket.onclose = () => {
    console.log('WebSocket连接关闭');
    heartCheck.reset();
    closeCallback && closeCallback();
  };

  // 连接错误
  websocket.onerror = () => {
    console.error('WebSocket连接错误');
    heartCheck.reset();
    errorCallback && errorCallback();
  };
}

// 发送消息
export function sendMessage(message) {
  if (websocket && websocket.readyState === websocket.OPEN) {
    try {
      websocket.send(message);
    } catch (e) {
      console.error('消息发送失败:', e);
    }
  }
}

// 关闭连接
export function closeWebSocket() {
  if (websocket) {
    websocket.close();
    websocket = null;
  }
  heartCheck.reset();
}

// 重新连接
function reconnect(deviceId) {
  if (websocket && websocket.readyState !== 3) {
    return;
  }
  console.log('尝试重新连接...');
  setTimeout(() => {
    initWebSocket(deviceId);
  }, 5000);
}

// 心跳检测
const heartCheck = {
  timeout: 60000, // 60秒
  timeoutObj: null,
  serverTimeoutObj: null,
  reset() {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start() {
    this.timeoutObj = setTimeout(() => {
      // 发送心跳消息
      sendMessage('ping');
      this.serverTimeoutObj = setTimeout(() => {
        // 如果超过一定时间还没收到回复，说明连接出现问题，关闭连接
        websocket.close();
      }, this.timeout);
    }, this.timeout);
  }
}; 